<template>
  <div class="merchant-apply">
    <!-- 搜索筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="申请状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" :value="0" />
            <el-option label="审核通过" :value="1" />
            <el-option label="审核拒绝" :value="2" />
            <el-option label="已取消" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item label="商家名称">
          <el-input
            v-model="queryParams.merchantName"
            placeholder="请输入商家名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleExport">
        <el-icon><Download /></el-icon>导出
      </el-button>
      <el-button type="success" @click="handleBatchApprove" :disabled="!selectedRows.length">
        <el-icon><Check /></el-icon>批量通过
      </el-button>
      <el-button type="danger" @click="handleBatchReject" :disabled="!selectedRows.length">
        <el-icon><Close /></el-icon>批量拒绝
      </el-button>
    </div>

    <!-- 申请列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="applyList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="merchantName" label="商家名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="contactName" label="联系人" width="120" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="businessType" label="经营类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getBusinessTypeTag(row.businessType)">
              {{ getBusinessTypeLabel(row.businessType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="申请状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180" />
        <el-table-column prop="auditTime" label="审核时间" width="180" />
        <el-table-column prop="auditor" label="审核人" width="120" />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              v-if="row.status === 0"
              link
              type="success"
              @click="handleApprove(row)"
            >
              通过
            </el-button>
            <el-button
              v-if="row.status === 0"
              link
              type="danger"
              @click="handleReject(row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialog.visible"
      :title="auditDialog.title"
      width="500px"
      append-to-body
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="80px"
      >
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="remark">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            placeholder="请输入审核意见"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitAudit">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="申请详情"
      width="800px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商家名称">{{ detailData.merchantName }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ detailData.contactName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailData.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="经营类型">
          {{ getBusinessTypeLabel(detailData.businessType) }}
        </el-descriptions-item>
        <el-descriptions-item label="申请状态">
          <el-tag :type="getStatusTag(detailData.status)">
            {{ getStatusLabel(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detailData.applyTime }}</el-descriptions-item>
        <el-descriptions-item label="营业执照" :span="2">
          <el-image
            :src="detailData.businessLicense"
            :preview-src-list="[detailData.businessLicense]"
            fit="contain"
            style="width: 200px; height: 200px"
          />
        </el-descriptions-item>
        <el-descriptions-item label="经营地址" :span="2">{{ detailData.address }}</el-descriptions-item>
        <el-descriptions-item label="经营范围" :span="2">{{ detailData.businessScope }}</el-descriptions-item>
        <el-descriptions-item label="申请说明" :span="2">{{ detailData.description }}</el-descriptions-item>
        <el-descriptions-item v-if="detailData.status !== 0" label="审核意见" :span="2">
          {{ detailData.remark }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Check, Close } from '@element-plus/icons-vue'
import {
  getMerchantApplyList,
  auditMerchantApply,
  exportMerchantApplyList
} from '@/api/merchant'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: undefined,
  dateRange: [],
  merchantName: ''
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 经营类型选项
const businessTypeOptions = [
  { label: '个人商户', value: 'personal' },
  { label: '企业商户', value: 'enterprise' },
  { label: '连锁商户', value: 'chain' }
]

// 状态选项
const statusOptions = [
  { label: '待审核', value: 0 },
  { label: '审核通过', value: 1 },
  { label: '审核拒绝', value: 2 },
  { label: '已取消', value: 3 }
]

// 列表数据
const loading = ref(false)
const applyList = ref([])
const total = ref(0)
const selectedRows = ref([])

// 审核对话框
const auditDialog = reactive({
  visible: false,
  title: '',
  type: 'single' // single: 单个审核, batch: 批量审核
})

// 审核表单
const auditFormRef = ref()
const auditForm = reactive({
  id: undefined,
  status: 1,
  remark: ''
})

// 审核表单校验规则
const auditRules = {
  status: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入审核意见', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 详情对话框
const detailDialog = reactive({
  visible: false
})

// 详情数据
const detailData = reactive({
  merchantName: '',
  contactName: '',
  contactPhone: '',
  businessType: '',
  status: 0,
  applyTime: '',
  businessLicense: '',
  address: '',
  businessScope: '',
  description: '',
  remark: ''
})

// 获取经营类型标签
const getBusinessTypeTag = (type) => {
  const map = {
    personal: 'info',
    enterprise: 'success',
    chain: 'warning'
  }
  return map[type] || 'info'
}

// 获取经营类型标签文本
const getBusinessTypeLabel = (type) => {
  const item = businessTypeOptions.find(item => item.value === type)
  return item ? item.label : type
}

// 获取状态标签
const getStatusTag = (status) => {
  const map = {
    0: 'info',
    1: 'success',
    2: 'danger',
    3: 'warning'
  }
  return map[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const item = statusOptions.find(item => item.value === status)
  return item ? item.label : status
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getMerchantApplyList({
      ...queryParams,
      startTime: queryParams.dateRange?.[0],
      endTime: queryParams.dateRange?.[1]
    })
    applyList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取商家入驻申请列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.status = undefined
  queryParams.dateRange = []
  queryParams.merchantName = ''
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 查看按钮操作
const handleView = async (row) => {
  try {
    const res = await getMerchantApplyDetail(row.id)
    Object.assign(detailData, res.data)
    detailDialog.visible = true
  } catch (error) {
    console.error('获取商家入驻申请详情失败:', error)
  }
}

// 审核按钮操作
const handleApprove = (row) => {
  auditDialog.type = 'single'
  auditDialog.title = '审核通过'
  auditForm.id = row.id
  auditForm.status = 1
  auditForm.remark = ''
  auditDialog.visible = true
}

// 拒绝按钮操作
const handleReject = (row) => {
  auditDialog.type = 'single'
  auditDialog.title = '审核拒绝'
  auditForm.id = row.id
  auditForm.status = 2
  auditForm.remark = ''
  auditDialog.visible = true
}

// 批量通过按钮操作
const handleBatchApprove = () => {
  auditDialog.type = 'batch'
  auditDialog.title = '批量审核通过'
  auditForm.status = 1
  auditForm.remark = ''
  auditDialog.visible = true
}

// 批量拒绝按钮操作
const handleBatchReject = () => {
  auditDialog.type = 'batch'
  auditDialog.title = '批量审核拒绝'
  auditForm.status = 2
  auditForm.remark = ''
  auditDialog.visible = true
}

// 提交审核
const submitAudit = async () => {
  if (!auditFormRef.value) return
  await auditFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (auditDialog.type === 'single') {
          await auditMerchantApply(auditForm.id, {
            status: auditForm.status,
            remark: auditForm.remark
          })
        } else {
          await Promise.all(
            selectedRows.value.map(row =>
              auditMerchantApply(row.id, {
                status: auditForm.status,
                remark: auditForm.remark
              })
            )
          )
        }
        ElMessage.success('审核成功')
        auditDialog.visible = false
        getList()
      } catch (error) {
        console.error('审核失败:', error)
        ElMessage.error('审核失败')
      }
    }
  })
}

// 导出按钮操作
const handleExport = async () => {
  try {
    await exportMerchantApplyList({
      ...queryParams,
      startTime: queryParams.dateRange?.[0],
      endTime: queryParams.dateRange?.[1]
    })
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.merchant-apply {
  padding: 20px;

  .filter-card {
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .table-card {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  // 响应式布局
  @media screen and (max-width: 768px) {
    .filter-form {
      .el-form-item {
        margin-right: 0;
        width: 100%;
      }
    }

    .action-bar {
      flex-wrap: wrap;
    }
  }
}
</style> 